package go_rpc

import (
	"fmt"
	log "github.com/sirupsen/logrus"
	json "gogame/lib"
	"gogame/server/network/tcp"
)

type GatewayAppInterface interface {
	Response(msg interface{}, err error, rid string, trans bool)
}

type RpcClient struct {
	RpcStruct
	TcpClient  *tcp.TcpClient // rpcClient 链接对象
	GatewayApp GatewayAppInterface
}

// NewRpcClient 实例化RpcClient
func NewRpcClient(listen, workerUrl string, gatewayApp GatewayAppInterface) *RpcClient {
	return &RpcClient{
		RpcStruct: RpcStruct{
			Type:    "rpcClient",
			Name:    fmt.Sprintf("rpcClient[%s]", listen),
			Address: workerUrl,
		},
		GatewayApp: gatewayApp,
	}
}

// Dial 链接worker
func (r *RpcClient) Dial(network, addr string) (err error) {
	r.Service = &rpcService{}

	r.rpcHandle = &rpcHandle{
		Name:    r.GetName(),
		Parent:  r,
		Service: r.Service,
		Process: 1,
	}

	r.TcpClient = &tcp.TcpClient{
		Handle: r.Handle,
	}
	err = r.TcpClient.Dial(network, addr)

	return err
}

// DoMessage 消息处理
func (r *RpcClient) DoMessage(message *Message) {
	var sendMsg interface{}
	msgErr := json.Loads(message.msg, &sendMsg)
	if msgErr == nil {
		r.GatewayApp.Response(sendMsg, nil, "", false)
	}

}

// OnClose 链接断开
func (r *RpcClient) OnClose(conn tcp.ConnChannelInterface) {
	err := conn.Close()
	if err != nil {
		log.Warning("RpcClient Close error!! -->", err)
	}
}

// Close 链接断开
func (r *RpcClient) Close() {
	r.TcpClient.Close()
}

func (r *RpcClient) Notice(methodName string, args ...interface{}) {
	r.rpcHandle.Notice(methodName, args...)
}

func (r *RpcClient) Call(methodName string, args ...interface{}) []byte {
	return r.rpcHandle.Call(methodName, args...)
}

func (r *RpcClient) CallBack(methodName string, kwArgs map[string]interface{}, args ...interface{}) {
	r.rpcHandle.CallBack(methodName, kwArgs, args...)
}
